
import java.util.Properties;

import java.util.Random;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class RequestInstallationActivity extends Activity{

	public RequestInstallationActivity(Properties props) {
		super(props);
	}
	 
	public ActivityResult execute(Resource db, Resource noss) {
		ActivityResult result = new ActivityResult();
		String address, description, date;
		int ticketId;
		Random generator = new Random();
		
		ticketId = generator.nextInt();
		address = 	(String)parameters.getProperty(Constants.STREET) + ", " +
					(String)parameters.getProperty(Constants.CITY) + ", " +
					(String)parameters.getProperty(Constants.STATE) + " " +
					(String)parameters.getProperty(Constants.ZIP);
		description = (String)parameters.getProperty(Constants.DESCRIPTION);
		
		Date d = new Date();
		DateFormat format = new SimpleDateFormat("MMddyy");
		date = format.format(d);
		
		String nossMessage = "";
		
		nossMessage += 	"<C4Message>\n\t<ServiceRequest name=\"Install\" uid=\"" + ticketId + "\">\n\t" +
						"\t<Param name=\"Location\" value=\"" + address + "\"/>\n\t" +
						"\t<Param name=\"Date\" value=\"" + date + "\"/>\n\t" +
						"</ServiceRequest>\n" + "</C4Message>";

		System.out.println();
		
		Noss myNoss = (Noss) noss;
		myNoss.sendMessage(nossMessage);
		
		ReplyManager replyManager = ReplyManager.getReplyManager();
		String reply = null;
		long i = 0; 
		while (((reply = replyManager.getReply()) == null) && (i <= 1000000000)){
			for(int j = 0; j <= 10; j++) {}
			i++;
		}
		
		if (i >= 1000000000) { //no reply from noss
			result.setResult(-1);
			result.addErrorMessage("Servers are down...");
			System.out.println("\nNo response recieved from Noss..");
		}
		else {
			System.out.println();
	
			CorporateDatabase database = (CorporateDatabase) db;
			String query = "";
			
			query += 	"INSERT INTO service_request_log (account_number,service_number,service_status,description,last_update) " +
						"VALUES (" + (String)parameters.getProperty(Constants.ACCOUNT_NUMBER) + "," +
						ticketId + ",'O',\"" + description + "\", CURDATE());"; 
			
			database.execute(query);
			
			result.setResult(0);
		}
		
		return result;
		
	}

	 
	public String getType() {
		return null;
	}
}
